﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using LitJson;
using SufeiUtil;

namespace Live
{
    public class LongzhuTv : BasePlatform
    {
        private readonly LongzhuTvRoom room = new LongzhuTvRoom();

        public override bool Init(string url)
        {
            room.ID = GetRoomId(url);
            if (string.IsNullOrEmpty(room.ID))
            {
                return false;
            }

            string html = ReqRoomInfo(string.Format("http://livestream.plu.cn/live/getlivePlayurl?roomId={0}",
                room.ID));

            JsonData data = JsonMapper.ToObject(html);
            room.LiveUrl = data["playLines"][0]["urls"][0]["securityUrl"].ToString();
            return true;
        }

        private string GetRoomId(string url)
        {
            HttpItem item = new HttpItem();
            item.Method = "GET";
            item.URL = url;
            item.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8";
            item.UserAgent =
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36";

            string html = mHelper.GetHtml(item).Html;
            Match match = Regex.Match(html, @"http://longzhu.com/streaming\?id=\d+");
            if (match.Success)
            {
                string streamUrl = match.Groups[0].Value;
                string[] urlPattern = streamUrl.Split(new char[] {'='});
                return urlPattern[1];
            }

            return "";
        }

        protected override string ReqRoomInfo(string url)
        {
            HttpItem item = new HttpItem();
            item.Method = "GET";
            item.URL = url;
            item.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8";
            item.UserAgent =
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36";

            return mHelper.GetHtml(item).Html;
        }

        public override bool IsLive()
        {
            return true;
        }

        public override Room GetRoomInfo()
        {
            return room;
        }

        public override string GetLivePlayUrl()
        {
            return room.LiveUrl;
        }
    }
}